<?php
include_once ROOT . '/model/dao/ProductDao.php';
$productDao = new ProductDao();
function updateCart(&$productCarts, $product, $number, $force = false)
{
    $number = (int)$number;
    if (empty($productCarts[$product->getId()]['qty']) && $number <= 0) {
        return;
    }
    if ($force) {
        $productCarts[$product->getId()]['qty'] = $number;
    } else {
        $productCarts[$product->getId()]['qty'] += $number;
    }

    if ($productCarts[$product->getId()]['qty'] > $product->getNumber()) {
        $productCarts[$product->getId()]['qty'] = $product->getNumber();
    }
    $productCarts[$product->getId()]['estimate'] = $product->getNumber() - $productCarts[$product->getId()]['qty'];
    $productCarts[$product->getId()]['price'] = $product->getPrice() * $productCarts[$product->getId()]['qty'];
    $productCarts[$product->getId()]['product'] = array('img' => getRoute('imgfromprod', $product->getId()),
        'title' => $product->getTitle(),
        'description' => $product->getDescription(),
        'price' => $product->getPrice(),
        'number' => $product->getNumber(),
        'id' => $product->getId());
    if ($productCarts[$product->getId()]['qty'] <= 0) {
        unset($productCarts[$product->getId()]);
    }

}

if (empty($_POST['id'])) {
    die(json_encode($_SESSION['cart']));
}
$id = (int)$_POST['id'];
$force = (boolean)$_POST['force'];
if (empty($_POST['qty']) && !$force) {
    $_POST['qty'] = 1;
}

$qty = (int)$_POST['qty'];
$product = $productDao->findById($id);
if (empty($product)) {
    die();
}
if (empty($_SESSION['cart']['products'])) {
    $_SESSION['cart']['products'] = array();
}

$productsCart = $_SESSION['cart']['products'];
updateCart($productsCart, $product, $qty, $force);
$totalPrice = 0;
$productsQty = 0;
foreach ($productsCart as $productCart) {
    $totalPrice += $productCart['price'];
    $productsQty += $productCart['qty'];
}
$_SESSION['cart']['products'] = $productsCart;
$_SESSION['cart']['productsQty'] = $productsQty;
$_SESSION['cart']['totalPrice'] = $totalPrice;
echo json_encode($_SESSION['cart']);
